<?php
/**
 * Created by PhpStorm.
 * User: huangshuaihui
 * Date: 2017/5/13
 * Time: 下午2:19
 */

namespace app\Http\Middleware\Admin;


use App\Http\Model\Admin\Menu;
use App\Http\Model\Admin\RoleMenu;
use App\Http\Model\Admin\User;
use app\Providers\PhpTreeServiceProvider;
use Closure;
use Config;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;

class AdminMidleware
{
    public function handle($request, Closure $next)
    {
        //非error页面才进行登录和权限验证
        if (Route::getCurrentRoute()->getName() != 'admin.error') {
            //判断是否登录
            if (!session('dmp_user')) {
                return redirect('admin/login');
            } //已登录的话 判断用户角色  获取用户权限菜单
            else {
                $admin_id = env('ADMINISTRATOR_ID') ? env('ADMINISTRATOR_ID') : 1;
                $this->current_user = session('dmp_user');
                $obj = [];
                //如果用户是管理员id 直接获取所有权限菜单
                if ($this->current_user['id'] == $admin_id) {
                    $this->current_user['is_admin'] = true;
                    $obj = self::getAllMenu();
                } else {
                    //否则就根据用户所在权限组获取权限菜单
                    $this->current_user['is_admin'] = false;
                    $obj = self::getUserMenu();
                }

                //判断当前访问路由是否有权限访问 TODO
                if(count($obj)) {
                    $is_pass = $this->current_user['is_admin'] ? true : self::checkRole($obj);
                    if ($is_pass) {
                        View::share('current_user_menu', PhpTreeServiceProvider::makeTree($obj));
                        View::share('current_user', $this->current_user);
                        View::share('current_route',Route::getCurrentRoute());
                        return $next($request);
                    } else {
                        return redirect('admin/error')->with('errors', Config::get('admin.errors.roleFail'));
                    }
                }
                else{
                    return redirect('admin/error')->with('errors', Config::get('admin.errors.roleFail'));
                }
            }
        } else {
            return $next($request);
        }
    }

    /*
     *  get currentuser's menu
     *
     * */
    public function getUserMenu()
    {
        $obj = [];
        $admin_role_id = env('ADMINISTRATOR_ROLE_ID') ? env('ADMINISTRATOR_ROLE_ID') : 1;
        $user = new User();
        $roles = $user->findOneById($this->current_user['id'])->roles;
        if (count($roles)){
            foreach ($roles as $key => $item) {
                if ($item['status'] != 1) {
                    unset($roles[$key]);
                }
            }
        }
        if (count($roles)) {
            $role_arr = [];
            foreach ($roles as $item) {
                array_push($role_arr, $item['id']);
            }
            //如果用户所在角色组包含管理员组 直接获取所有菜单权限
            if (in_array($admin_role_id, $role_arr)) {
                $this->current_user['is_admin'] = true;
                $obj = self::getAllMenu();
            } else {
                $role_menu = (new RoleMenu())->findByRoleIdArrs($role_arr);
                if ($role_menu) {
                    $menu_arr = [];
                    foreach ($role_menu as $item) {
                        array_push($menu_arr, $item['menu_id']);
                    }
                    $menu_list = (new Menu())->findByIdArrs(array_unique($menu_arr));
                    if ($menu_list) {
                        $obj = $menu_list;
                    }
                }
            }
        }
        return $obj;
    }

    /*
     *  get admin all menu
     * */
    public function getAllMenu()
    {
        return (new Menu())->findAllValid();
    }

    /*
     *  check role & route
     * */
    public function checkRole($role)
    {
        if ($role) {
            $route_arr = ['index'];
            foreach ($role as $item) {
                $item['route_name'] && array_push($route_arr, $item['route_name']);
            }
            $current_route_name = Route::getCurrentRoute()->getName();
            return in_array($current_route_name, self::addSomeRoute($route_arr));
        }
    }

    /*
     * add some edit route
     *
     * */
    public function addSomeRoute($route_arr)
    {
        $current_route = Route::getCurrentRoute();
        $current_route_name = $current_route->getName();
        $admin_id = env('ADMINISTRATOR_ID') ? env('ADMINISTRATOR_ID') : 1;
        $admin_role_id = env('ADMINISTRATOR_ROLE_ID') ? env('ADMINISTRATOR_ROLE_ID') : 1;
        //user.edit
        if (in_array('user.index', $route_arr)) {
            if($current_route->getParameter('user') != $admin_id){
                $current_route_name == 'user.edit' && array_push($route_arr, 'user.edit');
                $current_route_name == 'user.update' && array_push($route_arr, 'user.update');
                $current_route_name == 'user.destroy' && array_push($route_arr, 'user.destroy');
            }
        }

        if (in_array('user.create', $route_arr)) {
            array_push($route_arr, 'user.store');
        }

        //role.edit
        if (in_array('role.index', $route_arr)) {
            if($current_route->getParameter('role') != $admin_id){
                $current_route_name == 'role.edit' && array_push($route_arr, 'role.edit');
                $current_route_name == 'role.update' && array_push($route_arr, 'role.update');
                $current_route_name == 'role.destroy' && array_push($route_arr, 'role.destroy');
            }
            if ($current_route_name == 'role_menu' && $current_route->getParameter('role_id') != $admin_role_id) {
                array_push($route_arr, 'role_menu');
            }
            if ($current_route_name == 'role_menu_post' && $current_route->getParameter('role_id') != $admin_role_id) {
                array_push($route_arr, 'role_menu_post');
            }
        }

        if (in_array('role.create', $route_arr)) {
            array_push($route_arr, 'role.store');
        }

        //tourist.edit
        if (in_array('tourist.index', $route_arr)) {
            array_push($route_arr, 'tourist.edit');
            array_push($route_arr, 'tourist.show');
            array_push($route_arr, 'tourist.update');
        }

        if (in_array('tourist.create', $route_arr)) {
            array_push($route_arr, 'tourist.store');
        }

        //menu.edit
        if (in_array('menu.index', $route_arr)) {
            $current_route_name == 'menu.edit' && array_push($route_arr, 'menu.edit');
            $current_route_name == 'menu.update' && array_push($route_arr, 'menu.update');
            $current_route_name == 'menu.destroy' && array_push($route_arr, 'menu.destroy');
            $current_route_name == 'menu.sort' && array_push($route_arr, 'menu.sort');
        }

        if (in_array('menu.create', $route_arr)) {
            array_push($route_arr, 'menu.store');
        }
        return $route_arr;
    }
}